package com.yang.servlet;

import com.google.gson.Gson;
import com.yang.pojo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

@WebServlet("/ImageUploadServlet")
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收并保存图片
        Part part = request.getPart("brandLogoImg");

        //a给图片重新命名
        //拿到这个图片的名字
        String header = part.getHeader("Content-Disposition");
        //找到点这里的索引
        int index1 = header.lastIndexOf(".");
        //拿到双引号位置的索引
        int index2 = header.lastIndexOf("\"");
        //拿到.jpg
        String ext = header.substring(index1,index2);
        //拿到图片的名字
        String logoName = UUID.randomUUID().toString().replace("-","")+ext;
        //b获取categoryImage目录的路径（部署到服务器之后的路径）
        String dir = getServletContext().getRealPath("/upload");
        //c存储图片
        part.write(dir + "/" + logoName);
        //将分类信息保存到数据库
        String path = "upload/" + logoName;
        //b、将图片的路径响应给前端ajax请求
        ResultVO resultVO = new ResultVO(1000, path);
        String jsonStr = new Gson().toJson(resultVO);
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(jsonStr);
        writer.flush();
        writer.close();

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
